<template>
	<div class="qusetion-form">
		<el-form :model="form" :rules="rules" ref="form" label-width="100px" class="demo-form">
			<div class="form-wrap">
				<div class="form-wrap-title">
					<h2>基本信息</h2>
				</div>
				<div class="form-wrap-content">
					<el-row :gutter="20">
						<el-col :span="24">
							<el-form-item label="考试名称" prop="name">
								<el-input v-model="form.name"></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="考试分类" prop="examClassId">
								<ClassifySelect :defaultValue="form.examClassId" type="2" placeholder="请选择试卷分类" @emit="(v) => (form.examClassId = v)" />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="考试状态">
								<el-radio-group v-model="form.status">
									<el-radio label="1">正常</el-radio>
									<el-radio label="2">禁用</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="选择试卷" prop="paperId">
								<el-input placeholder="请输入选择试卷" v-model="curTast.name" class="input-with-select" @focus="selectTast()">
									<el-button slot="append" icon="el-icon-search" @click="selectTast()"></el-button>
								</el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="及格分数">
								<el-input-number v-model="form.passScore" controls-position="right" :min="0" :max="Number(tastTotalScore)"></el-input-number>
								<span class="txt-explain" style="margin-left: 10px">试卷总分 : {{ toFixeds(tastTotalScore) }}</span>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="试题排序">
								<el-radio-group v-model="form.subjectsSort">
									<el-radio label="1">固定排序</el-radio>
									<el-radio label="2">随机排序</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="试卷展示">
								<el-radio-group v-model="form.paperShowType">
									<el-radio label="1">整卷展示</el-radio>
									<el-radio label="2">单题展示</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="选项随机">
								<el-radio-group v-model="form.optionsSort">
									<el-radio label="1">固定排序</el-radio>
									<el-radio label="2">随机排序</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="可考次数">
								<el-input-number
									v-model="form.examMaxNum"
									controls-position="right"
									:min="1"
									:max="999"
									@blur="form.examMaxNum = checkNumber(form.examMaxNum, 1, 999)"
								></el-input-number>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item label="考试须知">
								<el-input type="textarea" :rows="2" placeholder="请输入考试须知" v-model="form.testInstructions"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</div>
			</div>
			<div class="form-wrap">
				<div class="form-wrap-title">
					<h2>时间设置</h2>
				</div>
				<div class="form-wrap-content">
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="开考时间" prop="startTime">
								<el-date-picker
									v-model="form.startTime"
									type="datetime"
									placeholder="选择开考时间"
									value-format="yyyy-MM-dd HH:mm:ss"
								></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="结束时间" prop="endTime">
								<el-date-picker
									v-model="form.endTime"
									type="datetime"
									placeholder="选择结束时间"
									value-format="yyyy-MM-dd HH:mm:ss"
								></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="考试时长">
								<el-input-number
									v-model="form.examDuration"
									controls-position="right"
									:min="0"
									:max="999"
									@blur="form.examDuration = checkNumber(form.examDuration, 0, 999)"
								></el-input-number>
								<span>分钟</span>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="公布成绩" prop="publishTime">
								<el-date-picker
									v-model="form.publishTime"
									type="datetime"
									placeholder="选择公布成绩时间"
									value-format="yyyy-MM-dd HH:mm:ss"
								></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="考试开始">
								<el-input-number
									v-model="form.joinLimited"
									controls-position="right"
									:min="0"
									:max="999"
									@blur="form.joinLimited = checkNumber(form.joinLimited, 0, 999)"
								></el-input-number>
								<span>分钟后禁止参加考试</span>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="开始考试">
								<el-input-number
									v-model="form.submitLimited"
									controls-position="right"
									:min="0"
									:max="999"
									@blur="form.submitLimited = checkNumber(form.submitLimited, 0, 999)"
								></el-input-number>
								<span>分钟内不允许交卷</span>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="公布答案">
								<el-radio-group v-model="form.publishAnswer">
									<el-radio label="1">公布</el-radio>
									<el-radio label="2">不公布</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="答卷详情">
								<el-radio-group v-model="form.publishHisPaper">
									<el-radio label="1">允许</el-radio>
									<el-radio label="2">不允许</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="答案解析">
								<el-radio-group v-model="form.publishAnalysis">
									<el-radio label="1">公布</el-radio>
									<el-radio label="2">不公布</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
					</el-row>
				</div>
			</div>
			<div class="form-wrap">
				<div class="form-wrap-title">
					<h2>考试对象</h2>
				</div>
				<div class="form-wrap-content">
					<el-row :gutter="20">
						<el-col :span="24">
							<el-form-item label="选择考生">
								<el-button type="primary" size="small" plain icon="el-icon-plus" @click="handleSelectStudent()">选择考生</el-button>
								<div class="student-wrap" v-if="examStudent.length">
									<p class="student-wrap-desc">已选考生：</p>
									<el-tag
										class="tag"
										size="medium"
										effect="plain"
										closable
										disable-transitions
										v-for="v in examStudent"
										:key="v.id"
										@close="handleCloseStudent(v)"
									>
										{{ v.name }}
									</el-tag>
								</div>
							</el-form-item>
						</el-col>
					</el-row>
				</div>
			</div>
			<el-form-item>
				<el-button type="custom" @click="submitForm('form')">提交</el-button>
			</el-form-item>
		</el-form>
		<TastSelect @emit="setTast" />
		<UserSelect :initialValue="initialValue" @e-userData="setUserId" />
	</div>
</template>
<script>
import Bus from '@/utils/bus.js';
export default {
	components: {
		ClassifySelect: () => import('../public/ClassifySelect.vue'),
		TastSelect: () => import('./TastSelect.vue'),
		UserSelect: () => import('@/components/userSelect')
	},
	data() {
		return {
			form: {
				//基本信息
				name: '', //考试名称
				examClassId: '', //考试分类id
				status: '1', //状态，1-正常，2-禁用
				paperId: '', //考试id
				passScore: '0', //及格分数
				subjectsSort: '1', //试题排序1-固定排序，2-随机排序
				paperShowType: '1', //考试展示1-整卷展示，2-单题展示
				optionsSort: '1', //选项随机1-固定排序，2-随机排序
				examMaxNum: '1', //可考次数
				testInstructions: '', //考试须知
				//时间设置
				startTime: '', //开考时间
				endTime: '', //结束时间
				examDuration: '0', //考试时长
				publishTime: '', //成绩公布
				joinLimited: '0', //参加限制
				submitLimited: '0', //交卷限制
				publishAnswer: '1', //公布答案1-公布答案（公布成绩后，同时公布正确答案）2-不公布答案（公布成绩后，不公布正确答案）
				publishHisPaper: '1', //答卷详情1-允许 考生查看历史答卷详情，2-不允许 考生查看历史答卷详情
				publishAnalysis: '1', //答案解析1-公布答案解析（公布成绩后，同时公布答案解析），2-不公布（公布成绩后，不公布答案解析）
				//考试对象
				testExamStudentVOList: [
					{
						ruleType: '1', //学生
						testExamRuleList: []
					}
				] //考试对象[{ruleType,[{id,name,contain}]},{type,[{id,contain}]}]
			},
			rules: {
				name: [{ required: true, message: '请输入考试名称', trigger: 'blur' }],
				examClassId: [{ required: true, message: '请选择考试分类', trigger: 'change' }],
				paperId: [{ required: true, message: '请选择试卷', trigger: 'change' }],
				startTime: [{ required: true, message: '请选择开考时间', trigger: 'blur' }],
				endTime: [{ required: true, message: '请选择结束时间', trigger: 'blur' }],
				publishTime: [{ required: true, message: '请选择公布成绩时间', trigger: 'blur' }]
			},
			curTast: {},
			initialValue: {
				userId: []
			}
		};
	},
	computed: {
		activeRow() {
			return this.$store.state.question.activeRow;
		},
		//试卷总分
		tastTotalScore() {
			return this.curTast.hasOwnProperty('id') ? this.curTast.totalScore : 0;
		},
		//所选学生
		examStudent() {
			this.initialValue.userId = this.form.testExamStudentVOList.filter((v) => v.ruleType == 1)[0].testExamRuleList;
			return this.initialValue.userId;
		}
	},
	watch: {
		activeRow: {
			immediate: true,
			handler(row) {
				this.init(row);
			}
		}
	},
	mounted() {},
	methods: {
		//显示弹窗
		init(row) {
			if (row.hasOwnProperty('id')) {
				this.form = { ...this.form, ...row };
				let { testPaper } = row;
				this.curTast = testPaper;
				this.form.paperId = testPaper.id;
				this.$set(this.form, 'id', row.id);
			} else {
				this.form = this.$options.data().form;
				this.$delete(this.form, 'id');
			}
		},
		//选择试卷
		selectTast() {
			this.$bus.$emit('showDialogTastSelect', this.form.paperId);
		},
		//设置试卷
		setTast(row) {
			this.curTast = row;
			this.form.paperId = row.id;
		},
		//选择学生
		handleSelectStudent() {
			Bus.$emit('userSelect');
		},
		//设置学生
		setUserId(v) {
			this.initialValue = v;
			let testExamRuleList = [];
			v.userId.forEach((item) => {
				let o = {
					contain: '1', //条件：1.包含 2.不包含
					id: item.id,
					name: item.userName
				};
				testExamRuleList.push(o);
			});
			this.form.testExamStudentVOList.forEach((item) => {
				if (item.ruleType == 1) {
					item.testExamRuleList = testExamRuleList;
				}
			});
		},
		//删除学生
		handleCloseStudent(row) {
			this.form.testExamStudentVOList.forEach((item) => {
				if (item.ruleType == 1) {
					item.testExamRuleList = item.testExamRuleList.filter((v) => v.id != row.id);
				}
			});
		},
		//判断考试时间
		timeCompare(date1, date2) {
			var oDate1 = new Date(date1);
			var oDate2 = new Date(date2);
			if (oDate1.getTime() >= oDate2.getTime()) {
				this.warnMsg('考试结束时间要大于开考时间');
			}
			return oDate1.getTime() < oDate2.getTime();
		},
		submitForm(formName) {
			this.$refs[formName].validate((valid) => {
				if (valid) {
					this.verifyForm();
				}
			});
		},
		async verifyForm() {
			let { startTime, endTime, passScore, examDuration, testExamStudentVOList } = this.form;
			let flag = this.timeCompare(startTime, endTime);
			if (!flag) return;
			passScore = parseFloat(passScore);
			examDuration = parseFloat(examDuration);
			if (passScore <= 0) {
				this.warnMsg('及格分数不能小于等于0');
				return;
			}
			if (examDuration <= 0) {
				this.warnMsg('考试时长不能小于等于0');
				return;
			}
			if (!testExamStudentVOList[0].testExamRuleList.length) {
				this.warnMsg('请选择考生');
				return;
			}
			let dispatchType = this.activeRow.hasOwnProperty('id') ? 'testExamUPDATE' : 'testExamADD';
			await this.$store.dispatch(dispatchType, this.form);
			this.$store.commit('SET_ACTIVENAME', 'manage');
		}
	}
};
</script>
<style scoped lang="scss">
.qusetion-form {
	max-width: 900px;
}
.form-wrap {
	margin-bottom: 20px;
	border: 1px solid #eee;
	.form-wrap-title {
		background: #eee;
		padding: 0 10px;
		height: 40px;
		line-height: 40px;
		h2 {
			font-size: 14px;
			color: #333;
		}
	}
	.form-wrap-content {
		padding: 10px;
	}
}
.student-wrap {
	margin: 10px 0;
	padding: 5px 10px;
	border-radius: 5px;
	border: 1px dashed #ddd;
	.student-wrap-desc {
		color: #666;
	}
	.tag {
		margin-right: 10px;
	}
}
</style>
